// This is main starting point
//
// Common package for project
package com.bren.android.androidproject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidProjectActivity extends Activity {
	// Instance variables
	private AudioManager audioManager;
	private TextView timerStatus;
	private TextView scheduleStatus;
	private TextView mapStatus;
	private TextView ringerStatus;
	private String[] ringerModes={"Silent","Vibrate","Normal"};
	
	SQLiteDatabase db=null;
		 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // start logging
        android.util.Log.w("Log active", "Log Active: " + System.currentTimeMillis() );
        
        //check version
        android.util.Log.w("Build: ", String.valueOf(Build.VERSION.SDK_INT ));
        
        //use AsyncTask to open DB for caching
        // now to prevent app stalling
     	MyDataLoader dataLoader = new MyDataLoader();// Asynchronous DB opener
     	dataLoader.execute();// only callable from UI main thread, parallel execution from pool of threads

        // get views
        timerStatus=(TextView)findViewById(R.id.timerstatus);
        scheduleStatus=(TextView)findViewById(R.id.schedulestatus);
        mapStatus=(TextView)findViewById(R.id.mapstatus);
        ringerStatus=(TextView)findViewById(R.id.ringerstatus);
        
        // use preferences to store what is enabled
        SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this);
        if (!prefs.contains("timerstatus")) {
        	// this is first run, make sure everything enabled
        	Editor ed= prefs.edit();
			ed.putBoolean("timerstatus", true);
			ed.putBoolean("schedulestatus", true);
			ed.putBoolean("mapstatus", true);
			ed.commit();	
        }
        
        // timer button
        Button button = (Button)findViewById(R.id.timerbutton);
        button.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        		SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(AndroidProjectActivity.this);
        		if(new Boolean(prefs.getBoolean("timerstatus", true))) {
        			// timer button clicked and is enabled
        			// APActivity 2 is timer
        			Intent intent = new Intent(AndroidProjectActivity.this, TimeoutActivity.class);		
            		startActivity(intent);
        		}else{
        			new AlertDialog.Builder(AndroidProjectActivity.this)
        			.setTitle("Timer Disabled")
        			.setMessage("The timer function is disabled. Re-enable?")
        			.setNeutralButton("Close",new DialogInterface.OnClickListener() {
        				public void onClick(DialogInterface dlg, int notUsed) {
        					// just close
        				}
        			})
        			.setPositiveButton("Re-enable",new DialogInterface.OnClickListener() {
        				public void onClick(DialogInterface dlg, int notUsed) {
        					// go to EditPreferences screen
        					startActivity(new Intent(AndroidProjectActivity.this, EditPreferences.class));
        				}
        			})
        			.show();
        		}		
        	}
        });
        
        // schedule button
        button = (Button)findViewById(R.id.schedulebutton);
        button.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        	SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(AndroidProjectActivity.this);
        	if(!(new Boolean(prefs.getBoolean("schedulestatus",true)))) {
        		Toast.makeText(AndroidProjectActivity.this, "Scheduler is off", Toast.LENGTH_SHORT).show();
        	}
        		// APActivity 3 is schedule
        		Intent intent = new Intent(AndroidProjectActivity.this, ScheduleActivity.class);
        		startActivity(intent);
        	}
        });
        
        // map button
        button = (Button)findViewById(R.id.mapbutton);
        button.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        		SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(AndroidProjectActivity.this);
            	if(!(new Boolean(prefs.getBoolean("mapstatus",true)))) {
            		Toast.makeText(AndroidProjectActivity.this, "Map service is off", Toast.LENGTH_SHORT).show();
            	}
    			//APActivity 4 is map
        		Intent intent = new Intent(AndroidProjectActivity.this, MyMapActivity.class);
        		startActivity(intent);
        	}
        });
        
        // preferences button
        button = (Button)findViewById(R.id.preferencesbutton);
        button.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        		startActivity(new Intent(AndroidProjectActivity.this, EditPreferences.class));
        	}
        });
       
        // read audio status
        audioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
        int i = audioManager.getRingerMode();
        ringerStatus.setText("Current ringer mode: " + ringerModes[i]);
        
        // start monitoring
        Intent service=new Intent(this, BootService.class);
        service.putExtra("extraData", "fromApp");
		startService(service);// start boot service if not started
       
        Log.d("TAG-AndroidProject", "finished main activity");  
    }// end main activity
   
    public boolean onCreateOptionsMenu(Menu menu) {
    	// need an icon for menu
    	menu.add(Menu.NONE, 1234, Menu.NONE, "Edit Preferences")
    	.setIcon(R.drawable.menu)
    	.setAlphabeticShortcut('e');
    	return (super.onCreateOptionsMenu(menu));
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()){
    		case 1234:
    			startActivity(new Intent(this, EditPreferences.class));
    			return(true);
    	}
    	return(super.onOptionsItemSelected(item));
    	}
    
    public void onResume() {
    	super.onResume();
    	// update UI
    	SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this);
    	timerStatus.setText(new Boolean(prefs.getBoolean("timerstatus", true)).toString());
    	scheduleStatus.setText(new Boolean(prefs.getBoolean("schedulestatus", true)).toString());
    	mapStatus.setText(new Boolean(prefs.getBoolean("mapstatus", true)).toString());
    	audioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
        int i = audioManager.getRingerMode();
        ringerStatus.setText("Current ringer mode: " + ringerModes[i]);
    }
    
    public void onDestroy(){
    	super.onDestroy();
    	// close DB if open
    	stopDb();
    }
    
    public void onConfigurationChanges(Configuration newConfig) {
    	// bye-bye landscape mode, who needs you anyway
    }
    
    // separate inner thread for opening database, task can be executed only once!
    // prevents stalling of main UI thread
 	// Param is DBname
 	// Progress is an integer, percentage complete
 	// Result is Boolean or Void
 	private class MyDataLoader extends AsyncTask<Void,Void,Void> {
 		// invoke on UI thread
 		protected void onPreExecute() {
 			//create progress bar on UI etc.
 		}
 		
 		// this is on separate thread
 		protected Void doInBackground(Void... v) {
 			// call publishProgress(Integer i); to publish on main UI thread
 			try {
 				db=(new Database(AndroidProjectActivity.this).getWritableDatabase());
 				android.util.Log.w("AndroidProjectActivity", "Database open");
 			} catch (SQLiteException e) {
 				android.util.Log.e("AndroidProjectActivity","Cannot open database");
 			}
 			return null;
 		}
 		
 		// invoked on main UI thread
 		protected void onProgressUpdate(Void... v) {
 			// show progress update
 			Toast.makeText(AndroidProjectActivity.this, "DB loading", Toast.LENGTH_SHORT).show();		
 		}
 		// invoked on main UI thread
 		protected void onPostExecute(Void v) {
 			// show results
 		}	
 	}// end AsyncTask
 	
 	protected void stopDb() {
		try {
			if(db!=null) {
				if(db.isOpen()) {
					db.close();
					android.util.Log.w("AndroidProjectActivity","Database closed");
				}else{
					android.util.Log.w("AndroidProjectActivity","Database already closed");
				}
				db=null;		
			}else{
				android.util.Log.w("AndroidProjectActivity","Database pointer was null");
			}	
		}catch (SQLiteException e) {
			android.util.Log.e("AndroidProjectActivity","Exception at stop database");
		}
	}
 	
}